<template>
  <div class="app-container">
    <div class="title">
      <div v-if="this.$route.params && this.$route.params.id">修改讲师</div>
      <div v-else>添加讲师</div>
    </div>
    <el-form
      ref="teacherForm"
      :model="teacher"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="讲师名称" prop="name">
        <el-input v-model="teacher.name" />
      </el-form-item>
      <el-form-item label="讲师排序" prop="sort">
        <el-input-number
          v-model="teacher.sort"
          controls-position="right"
          :min="1"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="讲师头衔" prop="level">
        <el-select v-model="teacher.level" placeholder="请选择">
          <el-option label="高级讲师" :value="1" />
          <el-option label="首席讲师" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="讲师资历" prop="career">
        <el-input v-model="teacher.career" />
      </el-form-item>
      <el-form-item label="讲师介绍" prop="intro">
        <el-input v-model="teacher.intro" type="textarea" :rows="10" />
      </el-form-item>
      <!-- 讲师头像 -->
      <el-form-item label="讲师头像">
        <!-- 头像缩略图 -->
        <PanThumb :image="teacher.avatar"></PanThumb>
        <el-button
          type="primary"
          class="el-icon-upload"
          @click="ImageCropperShow = true"
          >更换头像</el-button
        >
        <!-- 头像剪裁 -->
        <ImageCropper
          v-show="ImageCropperShow"
          @close="close"
          :width="300"
          :height="300"
          :key="ImageCropperKey"
          :url="`${BASE_URL}/file/upload?host=avatar`"
          field="file"
          @crop-upload-success="cropSuccess"
        >
        </ImageCropper>
      </el-form-item>
      <!-- 保存 -->
      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
  
  <script>
import teacherApi from "@/api/teacher";
import PanThumb from "@/components/PanThumb";
import ImageCropper from "@/components/ImageCropper";
export default {
  components: { PanThumb, ImageCropper }, //注册组件
  data() {
    return {
      BASE_URL: process.env.BASE_API,//获取dev配置文件中的Api地址
      ImageCropperKey:1,//头像剪裁组件key
      ImageCropperShow: false, //头像剪裁插件是否显示
      teacher: {
        avatar:
          "http://houpu-middle.oss-cn-hangzhou.aliyuncs.com/avatar/2022/10/avatar_default.png",
      }, //讲师数据
      rules: {
        //表单验证规则
        name: [
          { required: true, message: "请输入讲师姓名", trigger: "blur" },
          { max: 5, message: "长度最大为5个字符", trigger: "blur" },
        ],
        sort: [
          { type: "number", message: "排序必须是数字值", trigger: "blur" },
          { required: true, message: "请输入讲师序号", trigger: "blur" },
        ],
        level: [
          { required: true, message: "请选择讲师头衔", trigger: "change" },
        ],
        career: [
          { required: true, message: "请输入讲师资历", trigger: "blur" },
        ],
        intro: [{ required: true, message: "请输入讲师介绍", trigger: "blur" }],
      },
    };
  },
  //通过路由监视，触发页面初始化的方法
  watch: {
    $route(to, from) {
      this.init();
    },
  },
  created() {
    this.init();
  },
  methods: {
    //提交表单
    onSubmit() {
      //进行数据的合法性校验
      this.$refs["teacherForm"].validate((valid) => {
        if (valid) {
          //验证通过
          //判断执行的是添加还是更新
          if (this.teacher.id) {
            //调用更新讲师方法
            this.updateTeacher();
          } else {
            //调用添加讲师方法
            this.addTeacher();
          }
        } else {
          //格式校验失败
          console.log("error submit!!");
          return false;
        }
      });
      //判断执行的是添加还是更新
    },
    //添加讲师
    addTeacher() {
      //调用添加讲师的Api
      teacherApi.addTeacher(this.teacher).then((res) => {
        //提示成功信息
        this.$message({
          type: "success",
          message: "添加成功",
        });
        //跳转至讲师列表页面，通过编程式路由进行跳转
        this.$router.push({ path: "/teacher" });
      });
    },
    //更新教师
    updateTeacher() {
      //调用更新讲师的Api
      teacherApi.updateTeacher(this.teacher).then((res) => {
        //更新成功，提示信息
        this.$message({
          type: "success",
          message: "修改成功",
        });
        //跳转至讲师列表页面，通过编程式路由进行跳转
        this.$router.push({ path: "/teacher" });
      });
    },
    //初始化添加页面
    init() {
      //根据路由判断当前是添加还是修改
      if (this.$route.params && this.$route.params.id) {
        //执行更新操作
        // console.log("执行编辑");
        //根据id调用获取讲师信息的API
        const id = this.$route.params.id;
        teacherApi
          .getTeacher(id)
          .then((res) => {
            console.log(res);
            //当前讲师的信息绑定到表单中
            this.teacher = res.data;
          })
          .catch((err) => {
            this.$message({
              type: "error",
              message: "获取数据失败",
            });
          });
      } else {
        //执行添加操作
        // console.log("执行添加");
        //将teacher的属性赋值为空
        this.teacher = {
          avatar:
            "http://houpu-middle.oss-cn-hangzhou.aliyuncs.com/avatar/2022/10/avatar_default.png",
        };
        // console.log(teacher);
      }
    },
    //头像上传成功之后的回调方法
    cropSuccess(data) {
      //关闭头像剪裁插件
      this.ImageCropperShow = false;
      //显示上传后的头像
      this.teacher.avatar = data.ossUrl;

      //修改头像剪裁插件的key 使其初始化
      this.ImageCropperKey = this.ImageCropperKey + 1;
    },
    //关闭头像剪裁插件的显示
    close() {
      this.ImageCropperShow = false;
    },
  },
};
</script>
  
  <style scoped>
.line {
  text-align: center;
}
.title {
  font-weight: 700;
  font-size: 19px;
  line-height: 40px;
}
</style>
  
  